/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.support.inject;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.jianggujin.modulelink.action.JActionWrapper;
import com.jianggujin.modulelink.module.JModule;
import com.jianggujin.modulelink.support.JBeanProvider;

/**
 * 注入指定类型Bean数组
 * 
 * @author jianggujin
 *
 */
public class JInjectArray extends JAbstractInject {

    public JInjectArray(Object target, Field field, com.jianggujin.modulelink.support.annotation.JInject inject) {
        super(target, field, inject);
    }

    @Override
    protected Object handleValue(JBeanProvider provider, JModule<?> module) throws Exception {
        Class<?> fieldType = field.getType();
        Class<?> componentType = fieldType.getComponentType();
        int size = 0;
        Map<String, ?> values = provider.optBeansOfType(componentType);
        size += (values == null ? 0 : values.size());
        Collection<?> actions = null;
        if (JActionWrapper.class.equals(componentType)) {
            actions = module.getActionWrappers();
        } else {
            List<Object> filters = new ArrayList<Object>();
            for (JActionWrapper wrapper : module.getActionWrappers()) {
                if (componentType.isAssignableFrom(wrapper.getActionClass())) {
                    filters.add(wrapper.getAction());
                }
            }
            actions = filters;
        }
        size += (actions == null ? 0 : actions.size());
        if (size == 0) {
            return null;
        }
        Object value = Array.newInstance(componentType, size);
        int i = 0;
        if (values != null) {
            for (Object object : values.values()) {
                Array.set(value, i++, object);
            }
        }
        if (actions != null) {
            for (Object object : actions) {
                Array.set(value, i++, object);
            }
        }
        return value;
    }
}
